package com.xiaoming.controller;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.oauth.Oauth;
import com.xiaoming.base.ResponseBase;
import com.xiaoming.constants.Constants;
import com.xiaoming.entity.User;
import com.xiaoming.feign.UserServiceFegin;
import com.xiaoming.utils.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.LinkedHashMap;

/**
 * @author xiaoming
 * @Date 2020/3/12
 */
@Controller
public class LoginController {

    private static final String LOGIN = "login";

    private static final String INDEX = "redirect:/";


    private static final String ERROR = "error";

    private static final String RELATION = "qqrelation";

    @Autowired
    private UserServiceFegin userServiceFegin;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request) {
        String token = CookieUtil.getUid(request, Constants.COOKIE_MEMBER_TOKEN);
        if (StringUtils.isNotEmpty(token)){
            return INDEX;
        }
        return LOGIN;
    }

    @PostMapping("/login")
    public String login(User user, HttpServletRequest request, HttpServletResponse response) {
        // 1.调用登录接口
        ResponseBase login = userServiceFegin.login(user);
        if (!login.getCode().equals(Constants.HTTP_RES_CODE_200)) {
            request.setAttribute("error", "账号或密码错误!");
            return LOGIN;
        }
        // 2.登录成功，获取token信息
        LinkedHashMap linkedHashMap = (LinkedHashMap) login.getData();
        String token = (String) linkedHashMap.get(Constants.MEMBER_TOKEN);
        if (StringUtils.isEmpty(token)) {
            request.setAttribute("error", "token已经失效!");
            return LOGIN;
        }
        CookieUtil.addCookie(response, Constants.COOKIE_MEMBER_TOKEN, token, Constants.COOKIE_TOKEN_MEMBER_TIME);
        return INDEX;
    }


    @GetMapping("/localQqLogin")
    public String localQqLogin(HttpServletRequest request) throws QQConnectException {
        String authorizeURL = new Oauth().getAuthorizeURL(request);
        return "redirect:" + authorizeURL;
    }

    @GetMapping("/qqLoginCallback")
    public String qqLoginCallback(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession)
            throws QQConnectException {
        AccessToken tokenObj = new Oauth().getAccessTokenByRequest(request);
        if (tokenObj == null) {
            request.setAttribute("error", "qq授权失败!");
            return ERROR;
        }
        String accessToken = tokenObj.getAccessToken();
        if (StringUtils.isEmpty(accessToken)) {
            request.setAttribute("error", "qq授权失败!");
            return ERROR;
        }

        OpenID openID = new OpenID(accessToken);
        String userOpenID = openID.getUserOpenID();
        ResponseBase userByOpenId = userServiceFegin.findUserByOpenId(userOpenID);
        // 用戶沒有关联QQ账号
        if (userByOpenId.getCode().equals(Constants.HTTP_RES_CODE_201)) {
            // 跳转到管理账号
            httpSession.setAttribute("qqOpenid", userOpenID);
            return RELATION;
        }
        LinkedHashMap linkedHashMap = (LinkedHashMap) userByOpenId.getData();
        String token = (String) linkedHashMap.get(Constants.MEMBER_TOKEN);
        CookieUtil.addCookie(response, Constants.COOKIE_MEMBER_TOKEN, token, Constants.COOKIE_TOKEN_MEMBER_TIME);
        return INDEX;
    }


    @PostMapping("/qqRelation")
    public String qqRelation(User user, HttpServletRequest request, HttpServletResponse response, HttpSession httpSession) {
        // 1.获取openid
        String qqOpenid = (String) httpSession.getAttribute("qqOpenid");
        if (StringUtils.isEmpty(qqOpenid)) {
            request.setAttribute("error", "没有获取到openid");
            return "error";
        }
        // 2.调用登录接口，获取token信息
        user.setOpenid(qqOpenid);
        ResponseBase loginBase = userServiceFegin.qqLoginOpenId(user);
        if (!loginBase.getCode().equals(Constants.HTTP_RES_CODE_200)) {
            request.setAttribute("error", "账号或者密码错误!");
            return LOGIN;
        }

        LinkedHashMap linkedHashMap = (LinkedHashMap) loginBase.getData();
        String token = (String) linkedHashMap.get(Constants.MEMBER_TOKEN);
        if (StringUtils.isEmpty(token)) {
            request.setAttribute("error", "会话已经失效!");
            return LOGIN;
        }
        // 3.将token信息存放在cookie里面
        CookieUtil.addCookie(response, Constants.COOKIE_MEMBER_TOKEN, token, Constants.COOKIE_TOKEN_MEMBER_TIME);
        return INDEX;
    }

}
